package com.example.pay.service;
import com.alibaba.boot.dubbo.annotation.DubboConsumer;
import com.alipay.api.internal.util.AlipaySignature;
import com.example.pay.config.AlipayConfig;
import com.example.pojo.GdOrder;
import com.example.service.RpcAlipayService;
import com.example.service.RpcOrderService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
 * Created by Administrator on 2018/1/8.
 */
@Component
public class AlipayServiceImpl implements AlipayService {

    @DubboConsumer
    private RpcOrderService rpcQgOrderService;
    @DubboConsumer
    private RpcAlipayService rpcAlipayService;
    @Resource
    private AlipayConfig alipayConfig;

    @Override
    public void upDateOrder(String orderNo, String tradeNo) throws Exception {
        rpcAlipayService.upDateOrder(orderNo);
    }

    @Override
    public GdOrder loadQgOrderByOrderNo(String orderNo) throws Exception {
        return rpcQgOrderService.loadOrderByOrderNo(orderNo);
    }

    @Override
    public boolean processed(String orderNo) throws Exception {
        return rpcQgOrderService.processed(orderNo);
    }

    @Override
    public boolean asyncVerifyResult(Map<String, Object> params) throws Exception {
        Map<String, String> verifyParams = new HashMap<String, String>();
        Map<String, String[]> requestParams = (Map<String, String[]>)params.get("requestParams");
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            verifyParams.put(name, valueStr);
        }
        boolean verify_result = AlipaySignature.rsaCheckV1(verifyParams,alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), "RSA2");
        return verify_result;
    }
    @Override
    public boolean syncVerifyResult(Map<String, String[]> requestParams) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean verify_result = AlipaySignature.rsaCheckV1(params,
                alipayConfig.getAlipayPublicKey(), alipayConfig.getCharset(), "RSA2");
        return verify_result;
    }
}
